/***
 * @Description: 路由导航守卫
 * @Author: zhailei
 * @Date: 2021-06-02 13:38:09
 * @LastEditTime: 2021-09-15 09:35:50
 *
 * @FilePath: \vite-demoe:\wwwroot\Vue\\-cloud-vue\src\permission.js
 */
import Vue from "vue";
import router from "./router";
import store from "./store";
import storage from "vue-ls";
import { mergeI18nFromRoutes } from "@/utils/i18n";
import { initI18n } from "@/utils/i18n";
import { timeFix, flatTreeData } from "@/utils/util";
const i18n = initI18n("zh_CN", "zh_CN");
const options = {
  namespace: "vuejs__",
  name: "ls",
  storage: "local",
};

Vue.use(storage, options);
import NProgress from "nprogress"; // progress bar
import notification from "ant-design-vue/es/notification";
import { ACCESS_TOKEN } from "@/store/mutation-types";

NProgress.configure({
  showSpinner: false,
});
// NProgress Configuration
// 配置页面地址  白名单
const whiteList = [
  "login",
  "register",
  "404",
  "QywxLogin",
  "ForgetPwd",
  "DingtalkLogin",
  "qywxLoginBack",
  "ddLoginBack",
  "oauth2",
  "versionView",
  "versionCompare",
  "shareSceneView",
  "previewCad",
  "viewDataSetSingle",
  "shareExperienceView",
  "oidCallback",
  "projectHome",
  "largeScreen",
  "excessive",
  "previewCadBim",
  "viewDataSetSingleSimple",
]; // no redirect whitelist

const whitePathList = ["/singleProject/dataView"];
const loginRoutePath = "/user/login";
let defaultRoutePath = "/excessive";
const errPage = "/404";
const lockPage = "/lock"; //锁屏页
const token = Vue.ls.get(ACCESS_TOKEN);
store.dispatch("GetAllConfigData");

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (decodeURIComponent(to.path) === loginRoutePath) {
      next({
        path: defaultRoutePath,
      });
      NProgress.done();
    } else {
      if (store.getters.roles.length === 0) {
        //登录账号跳转页面权限
        let power = await store.dispatch("getAccountData");
        if (power.statusCode != 200) {
          notification.error({
            message: "系统提示",
            description: power.message,
            duration: 2,
          });
        }
        //查询项目树
        await store.dispatch("getTreeProjectData");
        //获取数据权限
        await store.dispatch("getPermissionIdentifyingByRoleId");
        //获取按钮权限数据
        await store
          .dispatch("getUserInForAndButtonPermissions", {
            token,
          })
          .then((res) => {
            // store.state.permission.addRouters = [];
            // store.state.permission.routers = [];
            // store.state.permission.menuData = [];
            const roles = res && res.role;
            store
              .dispatch("GenerateRoutes", {
                roles,
              })
              .then((roleData) => {
                // // 动态添加可访问路由表
                // store.getters.addRouters.forEach((item) => {
                //   router.addRoute(item);
                // });
                // // 提取路由国际化数据
                // mergeI18nFromRoutes(i18n, router.options.routes);
                // const redirect = decodeURIComponent(
                //   from.query.redirect || to.path
                // );
                // if (to.query.type === "login" || redirect == "/") {
                //   next({
                //     path: "/excessive",
                //   });
                // } else {
                //   next({
                //     path: redirect,
                //   });
                // }
                // // console.log(redirect, "redirect");
                // return;
                // 根据roles权限生成可访问的路由表
                // defaultRoutePath =
                //   store.getters.addRouters[0].path + "/excessive";
                defaultRoutePath = "/excessive";
                // 动态添加可访问路由表
                // router.addRoutes(store.getters.addRouters);
                store.getters.addRouters.forEach((item) => {
                  router.addRoute(item);
                });
                // 提取路由国际化数据
                mergeI18nFromRoutes(i18n, router.options.routes);
                // 请求带有 redirect 重定向时，登录自动重定向到该地址
                const redirect = decodeURIComponent(
                  from.query.redirect || to.path
                );
                if (to.query.type === "login") {
                  //   notification.success({
                  //     message: "欢迎",
                  //     description: `${timeFix()}，欢迎回来`,
                  //   });
                }
                if (decodeURIComponent(to.path) === redirect) {
                  if (to.path === "/excessive" || to.path === "/") {
                    next({
                      path: defaultRoutePath,
                    });
                    return;
                  }
                  next({
                    ...to,
                    replace: true,
                  });
                } else {
                  if (to.path === "/excessive" || to.path === "/") {
                    next({
                      path: defaultRoutePath,
                    });
                    return;
                  }
                  // 跳转到目的路由
                  next({
                    // path: redirect,
                    path:
                      from.path == loginRoutePath ? "/projectHome" : redirect,
                  });
                }
              });
          })
          .catch((err) => {
            //2024-08-08   放出提示消息
            notification.error({
              message: "系统提示",
              description: err.message,
              duration: 2,
            });
            store
              .dispatch("LogoutByErrorCode")
              .then(() => {})
              .catch(() => {})
              .finally(() => {
                // localStorage.clear();
                // sessionStorage.clear();
                // location.reload();
              });
          });
      } else {
        let isLock = localStorage.getItem("isLock");
        //如果系统激活锁屏，全部跳转到锁屏页
        if (isLock && to.path != lockPage && to.path != loginRoutePath) {
          history.pushState(null, null, document.URL);
          next({ path: lockPage });
        } else {
          next();
        }
      }
    }
  } else {
    sessionStorage.removeItem(process.env.VUE_APP_TBAS_KEY);
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      if (to.path === "/user/login") {
        // 获取系统配置
        store.dispatch("GetAllConfigData").finally((e) => {
          next();
        });
      } else {
        next();
      }
    } else {
      next({
        path: loginRoutePath,
        query: {
          redirect: to.path,
        },
      });
      NProgress.done();
    }
  }
});

router.afterEach((to) => {
  NProgress.done();
});
